package com.justnow.offer;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

/**
 * @author justnow
 * Created on 2020-09-10
 * Description
 */
public class Solution31 {

    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> res = new ArrayList<>();
        if (k <= 0 || n < k) {
            return res;
        }
        Deque<Integer> path = new ArrayDeque<>();
        dfs(n, k, 1, path, res);
        return res;

    }

    private void dfs(int n, int k, int begin, Deque<Integer> path, List<List<Integer>> res) {

        // 递归条件是：path的长度等于k
        if (path.size() == k) {
            res.add(new ArrayList<>(path));
            return;
        }

        // 遍历可能的搜索起点
        for (int i = begin; i <= n; i++) {
            // 向路径变量里添加一个数
            path.addLast(i);
            //System.out.println("递归之前 =>" + path);
            dfs(n, k, i + 1, path, res);
            path.removeLast();
            //System.out.println("递归之后 =>" + path);
        }
    }

    public static void main(String[] args) {
        Solution31 solution31 = new Solution31();
        int n = 4;
        int k = 2;
        List<List<Integer>> combine = solution31.combine(n, k);
        System.out.println(combine);
    }

/*
    public List<List<Integer>> combine2(int n, int k) {
        List<List<Integer>> res = new ArrayList<>();
        if (k <= 0 || n < k) {
            return res;
        }
        Deque<Integer> path = new ArrayDeque<>();
        //dfs2(n, k, 1, path, res);
        return res;
    }
*/

}
